package controller

import (
	"fmt"
	"net/http"
	"project1/validate"

	"strings"

	"github.com/kataras/iris/v12"
)

const (
	CodeSuccess     = 0
	CodeErrorNoresp = 1
	CodeErrorServer = 500
	MsgSuccess      = "成功"
	MsgError404     = "失败"
)

type BaseController struct {
	ValidateParams *validate.ValidateParams
}

func NewBaseController() *BaseController {
	return &BaseController{
		ValidateParams: validate.NewValidateParams(),
	}
}

/**
 * 接口统一返回方法
 * @param ctx:上下文
 * @param data:返回数据
 * @param err:错误
 */
func (b *BaseController) ApiReturn(ctx iris.Context, data any, err error) {
	code := CodeSuccess
	msg := MsgSuccess
	if err != nil {
		code = CodeErrorNoresp
		msg = fmt.Sprintf("%v", err)
	}
	ctx.JSON(iris.Map{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}

func (b *BaseController) GetCurrentIP(r http.Request) string {
	// 这里也可以通过X-Forwarded-For请求头的第一个值作为用户的ip
	// 但是要注意的是这两个请求头代表的ip都有可能是伪造的
	ip := r.Header.Get("X-Forwarded-For")
	if ip == "" {
		// 当请求头不存在即不存在代理时直接获取ip
		if r.RemoteAddr != "" {
			ip = strings.Split(r.RemoteAddr, ":")[0]
		}
	} else {
		ip = strings.Split(ip, ",")[0]
	}
	return ip
}
